#include <limits.h>  // INT_MIN,INT_MAX
#include <math.h>    // abs,pow

#include <algorithm>      // sort
#include <iostream>       // cout,cin
#include <string>         // string
#include <unordered_map>  // unordered_map
#include <unordered_set>  // unordered_set
#include <vector>         // vector

using namespace std;

// 如果x是2的幂则返回True，否则返回False
bool IsPowerOf2(int x) { return (x & (x - 1)) == 0; }

class Solution {
   public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int size = nums.size();

        // 初始化滑动窗口
        long now = 0;      //窗口元素和
        int i = 0, j = 0;  // 窗口下标:[i,j)
        while (j < size && now < target) {
            now += nums[j];
            j++;
        }

        // 处理所有元素的和小于target的情况
        if (now < target) {
            return 0;
        }

        // 滑动窗口计算最优解
        int ans = j - i;
        while (j <= size) {
            // 将窗口左边界向右移动1
            now -= nums[i];
            i++;

            // 调整窗口右边界以大于等于target
            while (j < size && now < target) {
                now += nums[j];
                j++;
            }

            // 处理剩余所有元素的和小于target的情况
            if (now < target) {
                break;
            }

            ans = min(ans, j - i);
        }

        return ans;
    }
};

int main() {
    Solution solution;
    vector<int> v1 = {2, 3, 1, 2, 4, 3};
    cout << solution.minSubArrayLen(7, v1) << endl;  // 2
    vector<int> v2 = {1, 4, 4};
    cout << solution.minSubArrayLen(4, v2) << endl;  // 1
    vector<int> v3 = {1, 1, 1, 1, 1, 1, 1, 1};
    cout << solution.minSubArrayLen(11, v3) << endl;  // 0
    return 0;
}